package com.tuweiya.study.springmvc002.eventBus.listener;

import com.google.common.eventbus.Subscribe;
import com.tuweiya.study.springmvc002.eventBus.bus.TimeEventBus;
import com.tuweiya.study.springmvc002.eventBus.event.CommonEvent;
import com.tuweiya.study.springmvc002.eventBus.event.TimeExpiringEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @Author: Mr_tu
 * @Date: Create in 15:49 2018/6/7
 * @Description: 消息监听器类
 *       消息监听器用于注册、监听和处理从消息总线接收到订阅消息
 *          |- 消息总线的注册在init()方法中实现
 *          |- 消息的订阅则通过@Subscribe注解方式实现。
 */
@Component
@Scope("singleton")
public class TimeTaskEventListener {

    private final Log logger = LogFactory.getLog(TimeTaskEventListener.class);

    @PostConstruct
    public void init(){
        logger.info("TimeTaskEventListener init()");
        TimeEventBus.register(this);
        logger.error("TimeEventBus.name = " + TimeEventBus.identifier());
    }

    @PreDestroy
    public void destroy(){
        logger.info("TimeTaskEventListener destroy()");
        TimeEventBus.unRegister(this);
    }

    @Subscribe
    public void printTimeTask(TimeExpiringEvent expiringEvent){
        System.out.println("Staring handle time expiring event");
        expiringEvent.handleTimeExpiringEvent();
        System.out.println("Finished handle time expiring event");

    }


    @Subscribe
    public void listen(CommonEvent commonEvent){
        System.out.println("TimeTaskEventListener start .....");
        commonEvent.something();
        System.out.println("TimeTaskEventListener end ....");
    }

}
